package com.clsz.service.impl;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.clsz.bean.bo.UserRegistBo;
import com.clsz.bean.po.UserInfo;
import com.clsz.mapper.UserMapper;
import com.clsz.service.UserService;
import com.clsz.utils.RedisUtils;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.frameworkset.util.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private RedisUtils redisUtils;
    @Autowired
    private UserMapper userMapper;

    /**
     *  1:注册成功 -1：验证码失败 -2：用户已存在
     * @param userRegistBo
     * @return注册
     */
    @Override
    public int regist(UserRegistBo userRegistBo) {

        String key = "SMS-Validate-" + userRegistBo.getUserLoginName();

        if (!redisUtils.hasKey(key) || !redisUtils.get(key).toString().equals(userRegistBo.getUserSMSValidate())) {
            return -1;
        }

        LambdaQueryWrapper<UserInfo> lambdaWrapper = new LambdaQueryWrapper<>();
        lambdaWrapper.eq(UserInfo::getUserLoginName, userRegistBo.getUserLoginName());
        List<UserInfo> userInfos = userMapper.selectList(lambdaWrapper);
        if (userInfos.size() > 0) {
            return -2;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserPhone(userRegistBo.getUserLoginName());
        userInfo.setUserLoginName(userRegistBo.getUserLoginName());
        //生成密码盐值
        String salt = UUID.randomUUID().toString();
        //加盐加密
        userInfo.setUserLoginPass(DigestUtils.md5DigestAsHex((userRegistBo.getUserLoginPass() + salt).getBytes()));
        //昵称
        userInfo.setUserNickName(userRegistBo.getUserNickName());
        //盐值
        userInfo.setUserPhone(salt);
        userInfo.setUserEnable((byte) 1);

        userMapper.insert(userInfo);
        return 1;
    }

    /**
     *
     * @param username
     * @param password
     * @return jwt令牌，null表示登录失败
     */
    @Override
    public String login(String username, String password) {
        //账户名称验证
        LambdaQueryWrapper<UserInfo> userInfoWrapper = new LambdaQueryWrapper<>();
        userInfoWrapper.eq(UserInfo::getUserLoginName, username);
        List<UserInfo> userInfos = userMapper.selectList(userInfoWrapper);

        if (userInfos.size() == 0) {
            System.out.println(username);
//            return "该用户未注册！！！";
            System.out.println("该用户未注册！！！");
            return null;
        }

        UserInfo user = userInfos.get(0);

        String md5_Password = DigestUtils.md5DigestAsHex((password + user.getUserPhone()).getBytes());
        if (!user.getUserLoginPass().equals(md5_Password)) {
            System.out.println("password error");
            return null;
        }
        //获取令牌，在redis中也要存储一份
        String token = JWT.create()
                .withAudience(JSON.toJSONString(user.getUserLoginName()))//荷载，登录当前对象
                .withIssuedAt(new Date())//签发时间
                .withExpiresAt(new Date(System.currentTimeMillis() + 60 * 1000 * 30))//过期时间
                .sign(Algorithm.HMAC256(user.getUserLoginPass()));
        redisUtils.set("Bearer " + token, user, 30 * 60);
        return token;
    }
}
